// pages/order/order-add/index.js
const util = require("../../../../utils/util.js");
Page({
    data: {
        is_onshow:false,
        color: wx.getExtConfigSync().color,
        address: null,
        cartData: [],
        totalPrice: 0,
        payment: [{
            name: '微信支付',
            payment_id: 1
        }], // 0余额，1微信，2支付宝，3货到付款
        pay_index: 0,
        coupon_id: 0, // 使用的优惠券id
        deliveryPrice: 0, // 满减价格
        couponPrice: 0, // 优惠券价格
        xiaojiPrice: 0, // 小计
        hejiPrice: 0, // 合计
        feePrice: 0, // 订单运费
        free_delivery: 0, // 是否包邮
        showModal: false,
        no_use_coupon: 0, // 不适用优惠券
        modalHeight: util.rpxToPx(-670) // 购物车弹窗高度
    },
    onLoad(options) {
        if (options.form_cart) {
            this.data.form_cart = Number(options.form_cart);
        }
        // 获取默认收货地址
        if (wx.getStorageSync("shippingAddress")) {
            this.setData({
                address: wx.getStorageSync("shippingAddress")
            });
        }
    },
    onShow() {
        if (this.data.form_cart) {
            this.data.cartData = JSON.parse(wx.getStorageSync('cart-data'));
        } else {
            this.data.cartData = JSON.parse(wx.getStorageSync('save-now'));
        }
        if (!this.data.is_onshow) {
            this.setData({
                is_onshow: true
            })
            this.getTotalprice();
        }
    },
    getTotalprice() {
        let cartData = [];
        this.data.cartData.forEach(val => {
            if (val.is_select) {
                cartData.push(val);
            }
        })
        this.setData({
            cartData: cartData
        });
        if (cartData.length) {
            let totalPrice = 0;
            let totalNum = 0;
            cartData.forEach(val => {
                totalPrice += (val.select_sku && val.select_sku.id ? val.select_sku.price : val.price) * val.num;
                totalNum += val.num;
            })
            this.data.xiaojiPrice = this.data.hejiPrice = totalPrice;
            // 运费
            let unite_fee = 0; // 全国统一运费
            cartData.forEach(val => {
                if (!val.fee_type) {
                    unite_fee += val.fee_price;
                }
            })
            // 计算满减
            wx.doodoo.fetch(`/shop/api/shop/fullCut/index`).then(res => {
                if (res && res.data.errmsg == 'ok') {
                    let delivery = res.data.data;
                    for (let val of delivery) {
                        if (totalPrice >= val.limit_price) {
                            this.data.deliveryPrice = val.price;
                            this.data.free_delivery = val.free_delivery;
                            break;
                        }
                    }
                    this.data.xiaojiPrice -= this.data.deliveryPrice;
                    this.data.hejiPrice -= this.data.deliveryPrice;
                    this.data.hejiPrice += this.data.free_delivery ? 0 : unite_fee;

                    this.setData({
                        deliveryPrice: this.data.deliveryPrice,
                        feePrice: this.data.free_delivery ? 0 : unite_fee
                    })
                    this._coupon(totalPrice, this.data.deliveryPrice, this.data.xiaojiPrice, this.data.hejiPrice);
                } else {
                    this._coupon(totalPrice, this.data.deliveryPrice, this.data.xiaojiPrice, this.data.hejiPrice);
                }
            })
            this.setData({
                totalPrice: totalPrice,
                totalNum: totalNum
            })
        }
    },
    _coupon(totalPrice, deliveryPrice, xiaojiPrice, hejiPrice) {
        // 获取可用优惠券
        wx.doodoo.fetch(`/shop/api/shop/coupon/index?totalprice=${(totalPrice - deliveryPrice).toFixed(2)}`).then(res => {
            if (res && res.data.errmsg == 'ok' && res.data.data.length) {
                let coupon = res.data.data;
                coupon.sort((a, b) => {
                    if (a.coupon && a.coupon.limit_price && b.coupon && b.coupon.limit_price) {
                        return a.coupon.limit_price < b.coupon.limit_price; // 从大到小排列
                    }
                })
                let length = 2; // 默认设置两个数字宽度 22 50 86 75
                length = String(coupon[0].coupon.price).length;
                for (let val of coupon) {
                    val.is_select = 0;
                    val.coupon.last_time = val.coupon.ended_at.substr(0, 10);
                    val.coupon.start_time = val.coupon.started_at.substr(0, 10);
                }
                for (let val of coupon) {
                    if (totalPrice - deliveryPrice >= val.coupon.limit_price) {
                        val.is_select = 1;
                        this.data.couponPrice = val.coupon.price;
                        this.data.coupon_id = val.id;
                        break;
                    }
                }
                xiaojiPrice -= this.data.couponPrice;
                hejiPrice -= this.data.couponPrice;
                xiaojiPrice = Number(xiaojiPrice.toFixed(2));
                hejiPrice = Number(hejiPrice.toFixed(2));
                this.setData({
                    xiaojiPrice: xiaojiPrice,
                    hejiPrice: hejiPrice,
                    length: length,
                    coupon: coupon,
                    couponPrice: this.data.couponPrice
                })
            } else {
                xiaojiPrice = Number(xiaojiPrice.toFixed(2));
                hejiPrice = Number(hejiPrice.toFixed(2));
                this.setData({
                    xiaojiPrice: xiaojiPrice,
                    hejiPrice: hejiPrice,
                    coupon: []
                })
            }
        });
    },
    hideModal() {
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: 'linear'
        })
        animation.translateY(0).step();
        this.setData({
            animationData: animation.export()
        })
        setTimeout(() => {
            animation.translateY(this.data.modalHeight).step();
            this.setData({
                animationData: animation.export(),
                showModal: false
            })
        }, 200)
    },
    showModal(e) {
        let animation = wx.createAnimation({
            duration: 200, // 动画持续时间
            timingFunction: 'linear' // 定义动画效果，当前是匀速
        })
        animation.translateY(0).step();
        this.setData({
            animationData: animation.export(), // 通过export()方法导出数据
            showModal: true
        })
        // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
        setTimeout(() => {
            animation.translateY(this.data.modalHeight).step();
            this.setData({
                animationData: animation.export()
            })
        }, 200)
    },
    couponSelect(e) {
        const item = e.currentTarget.dataset.item;
        let coupon = this.data.coupon;
        for (let val of coupon) {
            if (val.id == item.id) {
                val.is_select = 1;
                this.data.couponPrice = val.coupon.price;
                this.data.coupon_id = val.id;
            } else {
                val.is_select = 0;
            }
        }
        this.setData({
            no_use_coupon: 0,
            coupon: coupon,
            couponPrice: this.data.couponPrice
        })
        this.hideModal();
    },
    noUseCoupon() {
        let coupon = this.data.coupon;
        if (coupon) {
            for (let val of coupon) {
                val.is_select = 0;
            }
        }
        this.setData({
            coupon: coupon ? coupon : [],
            no_use_coupon: 1,
            couponPrice: 0,
            coupon_id: 0
        })
        this.hideModal();
    },
    // 选择收货地址
    goAddress: function(e) {
        wx.removeStorageSync("shippingAddress");
        let that = this;
        wx.chooseAddress({
            success: function(res) {
                let _address = {
                    userName: res.userName,
                    telNumber: res.telNumber,
                    nationalCode: res.nationalCode,
                    addr: res.provinceName + res.cityName + res.countyName + res.detailInfo
                };
                wx.setStorageSync("shippingAddress", _address);
                // 计算运费
                that.setData({
                    address: _address
                });
            }
        });
    },
    // 选择支付方式
    bindPickerChange: function(e) {
        // payment_id 0余额，1微信，2支付宝，3货到付款）
        this.setData({
            pay_index: Number(e.detail.value)
        });
    },
    // 填写备注信息
    bindinput: function(e) {
        this.data.remark_data = e.detail.value;
    },
    // 新增订单
    submitOrder: function(e) {
        // 收货地址  （orderData.contact）
        let address = wx.getStorageSync("shippingAddress");
        if (!address.addr) {
            wx.showModal({
                title: "提示",
                content: "请选择收货地址",
                showCancel: false
            });
            return;
        }
        let cartdata = [];
        this.data.cartData.forEach(val => {
            cartdata.push({
                id: val.id,
                sku_id: val.select_sku && val.select_sku.id ? val.select_sku.id : 0,
                num: val.num
            })
        })
        let submit = {
            cartdata: cartdata,
            contact: address,
            couponId: this.data.coupon_id,
            remark: this.data.remark_data
        };
        wx.doodoo.fetch(`/shop/api/shop/order/order/add`, {
            method: "POST",
            data: submit
        }).then(res => {
            if (res && res.data.errmsg == 'ok') {
                // 删除已提交的购物车数据
                this.hideModal();
                this.del();
                this.wxPay(res.data.data);
            } else {
                wx.showModal({
                    title: "提示",
                    content: res.data && res.data.errmsg ? res.data.errmsg : "参数有误",
                    showCancel: false
                });
            }
        });
    },
    // 微信支付
    wxPay(data) {
        // payment_id ： 0余额 1微信 2支付宝 3货到
        wx.doodoo.fetch(`/app/pay/wxpay/index?id=${data.trade_id}`).then(res => {
            if (res && res.data.errmsg == 'ok') {
                let response = res.data.data;
                let timeStamp = response.timeStamp;
                //可以支付
                wx.requestPayment({
                    timeStamp: timeStamp.toString(),
                    nonceStr: response.nonceStr,
                    package: response.package,
                    signType: response.signType,
                    paySign: response.paySign,
                    success: () => {
                        // this.send_tplmsg(response.package, data.id); // 支付成功，发送支付成功模板
                        wx.redirectTo({
                            url: `../order-detail/index?order_id=${data.id}`
                        });
                    },
                    fail: () => {
                        wx.redirectTo({
                            url: `../order-detail/index?order_id=${data.id}`
                        });
                    }
                });
            } else {
                wx.showModal({
                    title: "提示",
                    content: res.data.errmsg,
                    showCancel: false,
                    success: function(res) {
                        if (res.confirm) {
                            wx.redirectTo({
                                url: `../order-detail/index?order_id=${data.id}`
                            });
                        }
                    }
                });
            }
        });
    },
    del: function() {
        // 删除已提交的购物车数据
        wx.removeStorageSync('save-now');
        let cartData = wx.getStorageSync('cart-data') ? JSON.parse(wx.getStorageSync('cart-data')) : [];
        if (cartData.length) {
            let i = cartData.length;
            while (i--) {
                if (cartData[i].is_select) {
                    cartData.splice(i, 1);
                }
            }
        }
        wx.setStorageSync("cart-data", JSON.stringify(cartData));
    },
    // 发送模板消息
    send_tplmsg: function(formId, order_id) {
        formId = formId.substring(10);
        wx.doodoo.fetch("/api/order/sendPayTpl", {
            method: "GET",
            data: {
                formId: formId,
                orderId: order_id
            }
        }, res => {
            console.log("发送模板消息", res);
        });
    }
});